package com.justnow.offer;

/**
 * @author justnow
 * Created on 2020-09-20
 * Description
 */
public class Solution62 {
    public int hammingWeight(int n) {
        int sum = 0;
        while (n != 0) {
            sum++;
            n &= (n - 1);
        }
        return sum;
    }

    public int hammingWeight2(int n) {
        int sum = 0;
        while (n != 0) {
            sum += n & 1;
            n = n >> 1;
        }
        return sum;
    }

    /**
     *
     * @param n
     * @return
     *
     *
     * 举个例子
     *
     *
     *    n = 1100
     *  n-1 = 1011
     *  此时两者上下进行与运算，那么n&n-1,将会把n中从右到左中的第一个1转换为0，即
     *  n = n & (n - 1) = 1000
     *      n = 1000
     *  n - 1 = 0111
     *  然后两者与运算，最终的结果就是0，也就是把n的第4为的1转化为0，所以这就是结果了
     *
     **/
    public int hammingWeight3(int n) {
        int sum = 0;
        while (n != 0) {
            sum++;
            n = n & (n - 1);
        }
        return sum;
    }

}
